package com.ztomorrow.ying_cun_plus.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.ztomorrow.ying_cun_plus.dao.mapper.BookChapterMapper;
import com.ztomorrow.ying_cun_plus.dao.mapper.BookInfoMapper;
import com.ztomorrow.ying_cun_plus.dao.po.BookChapter;
import com.ztomorrow.ying_cun_plus.dao.po.BookInfo;
import com.ztomorrow.ying_cun_plus.dto.resp.BookInfoRespDto;
import com.ztomorrow.ying_cun_plus.utils.CacheUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import static com.ztomorrow.ying_cun_plus.constant.front.CacheConstant.*;

@Component
@RequiredArgsConstructor
public class BookInfoCacheManager {
    private final CacheUtils cacheUtils;
    private final BookInfoMapper bookInfoMapper;

    private final BookChapterMapper bookChapterMapper;

    /**
     * 根据小说ID获取，书籍信息
     */
    public BookInfoRespDto getBookInfo(Long bookId) {
        BookInfoRespDto cache = cacheUtils.getCacheOne(
                v -> BeanUtil.copyProperties(v, BookInfoRespDto.class),
                CAFFEINE_BOOK_INFO + bookId, REDIS_BOOK_INFO + bookId,
                v -> JSONUtil.toBean(v, BookInfoRespDto.class));
        if (cache != null) return cache;
        // 查询基础信息
        BookInfo bookInfo = bookInfoMapper.selectById(bookId);
        // 查询首章ID
        BookChapter one = new LambdaQueryChainWrapper<>(bookChapterMapper)
                .eq(BookChapter::getBookId, bookId)
                .orderByAsc(BookChapter::getChapterNum)
                .last("limit 1")
                .one();
        // 组装响应对象
        BookInfoRespDto bookInfoRespDto = BeanUtil.copyProperties(bookInfo, BookInfoRespDto.class);
        bookInfoRespDto.setFirstChapterId(one.getId());
        cacheUtils.saveCacheOne(bookInfoRespDto,
                CAFFEINE_BOOK_INFO + bookId,
                REDIS_BOOK_INFO + bookId, REDIS_BOOK_INFO_TTL,
                JSONUtil::toJsonStr);
        return bookInfoRespDto;
    }

}
